#-------------------------------------------------------------------------------
# Name:        zip_to_xml_converter.py
# Purpose:     Classes to extract XML from LibreOffice plugin-generated ZIP file
#
# Authors:     John Graves <john.graves@slidespeech.com>
#
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import os, sys
from converter import Converter
from zipfile import ZipFile

class ZipToXMLConverter(Converter):
    def __init__(self, zipFile, xmlPath=None, previous=None):
        Converter.__init__(self, previous)
        self._zipFile = zipFile
        if xmlPath is None:
            self._xmlPath = self.tempDir()
        else:
            self._xmlPath = xmlPath
        self._xmlFile = 'slide-notes.xml'

    def _convertImpl(self):
        """Extracts the XML file
        CONTENTS/slide-notes.xml
        from the given ZIP file to indicated path"""
        try:
            zip = ZipFile(self._zipFile,'r')
            f = zip.extract(u"CONTENTS/slide-notes.xml", self._xmlPath)

        except Exception as ex:
            raise RuntimeError("Could not extract CONTENTS/contents.xml " + \
                               "from ZIP file {0} to path {1}".format(self._zipFile, self._xmlPath))

        self._xmlPath = os.path.join(self._xmlPath,'CONTENTS')

    def xmlPath(self):
        return self._xmlPath

    def xmlFile(self):
        return self._xmlFile

if __name__ == "__main__":
    # a simple test/demo
    # into CONTENTS
#    c = ZipToXMLConverter(sys.argv[1], os.getcwd())
    # into tmp\CONTENTS
    c = ZipToXMLConverter(sys.argv[1])
    c.convert()
    print("XML Path: {0}".format(c.xmlPath()))
    print("XML File: {0}".format(c.xmlFile()))